package com.idrive.database.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.idrive.database.DatabaseHelper;
import com.idrive.database.DatabaseUtility;
import com.idrive.database.dto.CallLog;

public class CallLogDao {
	// Database fields
	private SQLiteDatabase database;
	private String[] allColumns = { DatabaseUtility.COLUMN_CALL_LOG_TIME, DatabaseUtility.COLUMN_CALL_LOG_EVENT,
	        DatabaseUtility.COLUMN_CALL_LOG_TELEPHONE };

	public CallLogDao(Context context) {
		DatabaseHelper.init(context);
		database = DatabaseHelper.getInstance().getWritableDatabase();
	}

	public void addCallLog(CallLog callLog) {
		ContentValues values = new ContentValues();
		values.put(DatabaseUtility.COLUMN_CALL_LOG_TIME, callLog.getTime());
		values.put(DatabaseUtility.COLUMN_CALL_LOG_TELEPHONE, callLog.getTelephone());
		values.put(DatabaseUtility.COLUMN_CALL_LOG_EVENT, callLog.getEvent());

		database.insert(DatabaseUtility.TABLE_CALL_LOG, null, values);

	}

	public List<CallLog> getCallLog() {
		List<CallLog> list = new ArrayList<CallLog>();
		Cursor cursor = database.query(DatabaseUtility.TABLE_CALL_LOG, allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			CallLog log = new CallLog();
			log.setTime(cursor.getString(cursor.getColumnIndex(DatabaseUtility.COLUMN_CALL_LOG_TIME)));
			log.setEvent(cursor.getString(cursor.getColumnIndex(DatabaseUtility.COLUMN_CALL_LOG_EVENT)));
			log.setTelephone(cursor.getString(cursor.getColumnIndex(DatabaseUtility.COLUMN_CALL_LOG_TELEPHONE)));
			list.add(log);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return list;
	}
}
